import { Dep } from "./dep";
export function observer(data, asRoot) {
  let ob;
  ob = new Observer(data);
}

export class Observer {
  value: any;
  deps: [];
  constructor(value: any) {
    // this.value = value;
    this.deps = null;
    def(value, "__ob__", this);
    this.walk(value);
  }

  walk(value: Object) {
    let keys = Object.keys(value),
      length = keys.length;
    while (length--) {
      defineReactive(value, keys[length], value[keys[length]], this);
    }
  }
}

function def(target, key, value, enumerable?) {
  Object.defineProperty(target, key, {
    value: value,
    enumerable: enumerable,
    writable: true,
    configurable: true,
  });
}

function defineReactive(obj, key, value, ob) {
  let dep = new Dep();
  ob.deps = dep;
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    set(val) {
      if (val === value) {
        return;
      }
      value = val;
      dep.notify();
      return val;
    },
    get() {
      dep.depend();
      return value;
    },
  });
}
